import {
  FlatList,
  Image,
  NativeScrollEvent,
  NativeSyntheticEvent,
  ScrollView,
  StyleSheet,
  Text,
  View
} from "react-native";
import React, { MutableRefObject, useCallback, useEffect, useRef, useState } from "react";
import { articleRecommend, literatureRecommend } from "../api";
import { useFocusEffect } from "@react-navigation/native";
import { windowHeight, windowWidth } from "../util";
import LiteratureList from "../components/LiteratureList";
import { ArticleType, LiteratureType } from "../util/publicType";
import Loading from "../components/Loading";
import renderItem from "../components/LiteratureList";
import Empty from "../components/Empty";
import ListFooter from "../components/ListFooter";

const Home = () => {
  // 滚动ele
  const scrollEle = useRef<ScrollView | null>(null);

  // 文章数据
  const [articleData, setArticleData] = useState<Array<ArticleType>>([]);

  // 文献数据
  const [literatureData, setLiteratureData] = useState<Array<LiteratureType>>([]);

  // 当前索引
  const [currentIndex, setCurrentIndex] = useState<number>(0);

  // 定时器
  const [intervalEvent, setIntervalEvent] = useState<any>(null);

  // 是否加载完成
  const [isLoading, setIsLoading] = useState<boolean>(true);

  // 是否加载完成
  useFocusEffect(useCallback(() => {
    // 获取文章
    getArticleData();
  }, []));

  // 页面离开时，清除定时器
  useFocusEffect(useCallback(() => {
    return () => {
      // 页面离开时，清除定时器任务
      if (intervalEvent) {
        // 清除定时器
        clearInterval(intervalEvent);
        // 赋null
        setIntervalEvent(null);
      }
    };
  }, [intervalEvent]));

  // 监听索引变化执行移动动作
  useEffect(() => {
    // 判断当前是否超出最大移动值
    if ((currentIndex > articleData.length - 1 || currentIndex < 0)) {
      // 如果超出，更改索引值为0
      setCurrentIndex(0);
    } else {
      // 沒超出 滚动到指定位置
      scrollEle.current?.scrollTo({
        x: currentIndex * windowWidth,
        y: 0
      });
    }
  }, [currentIndex, articleData]);

  // 自动轮播
  const autoSwiper = (data: Array<ArticleType>) => {
    // 开启定时器
    const interval = setInterval(() => {
      // 动态更新状态
      if (currentIndex < data.length) {
        setCurrentIndex(v => v + 1);
      } else {
        setCurrentIndex(0);
      }
    }, 5000);
    // 保存定时器，离开页面时，清除需要
    setIntervalEvent(interval);
  };

  // 文章获取
  const getArticleData = async () => {
    setIsLoading(true);
    const r = await articleRecommend();
    // 获取文献
    await getLiteratureData();
    setArticleData(r.data);
    // 开启定时器
    autoSwiper(r.data);
    // 关闭加载
    setIsLoading(false);
  };

  // 文献获取
  const getLiteratureData = () => {
    literatureRecommend().then(r => {
      setLiteratureData(r.data);
    });
  };

  // 結束拖动，重置当前索引
  const onScrollEndDrag = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    // 当前移动的x距离
    const currentDistance: number = event.nativeEvent.contentOffset.x;
    // 获取触摸移动的值
    const velocityX: number = event?.nativeEvent?.velocity?.x ?? 0;
    // 此时已分页，直接更改索引
    if (currentDistance > windowWidth) {
      if (velocityX <= 0) {
        setCurrentIndex(Math.floor(currentDistance / windowWidth) + 1);
      } else {
        setCurrentIndex(Math.floor(currentDistance / windowWidth));
      }
    } else {
      // 当滑动距离大于其一半时，再更改索引
      if (currentDistance >= (windowWidth / 2)) {
        // 判断左滑还是右滑，负数左滑
        if (velocityX <= 0) {
          setCurrentIndex(v => v + 1);
        } else {
          setCurrentIndex(v => v - 1);
        }
      } else {
        setCurrentIndex(0);
      }
    }
  };

  return (
    <View style={{ minHeight: windowHeight, position: "relative" }}>
      <Loading isLoading={isLoading} />
      {/*轮播*/}
      <ScrollView horizontal
                  ref={scrollEle}// 分页
                  pagingEnabled={true}// 样式
                  style={bannerStyles.box}// 禁用js平移监听器
                  disableScrollViewPanResponder={true}// 隐藏水平滚动条
                  showsHorizontalScrollIndicator={false}// 左右开端末尾可再拉动一截
                  alwaysBounceHorizontal={true}// 按页滚动
                  onScrollEndDrag={onScrollEndDrag}// 结束拖动
      >
        {
          articleData.map((v, index) => {
            return (
              <View key={v.id} style={bannerStyles.item}>
                <Image
                  style={bannerStyles.img}
                  source={{
                    uri: v.cover.path
                  }}
                />
                <Text style={bannerStyles.title}>{v.name}</Text>
              </View>
            );
          })
        }
      </ScrollView>
      {/* 指示点 */}
      <View style={indicateStyles.box}>
        <View style={indicateStyles.inner}>
          {
            articleData.map((v, i) => {
              return (
                <View key={v.id} style={i === currentIndex ? indicateStyles.active : indicateStyles.item}></View>
              );
            })
          }
        </View>
      </View>
      {/* 文献列表 */}
      <View style={literatureStyles.box}>
        <Text style={literatureStyles.title}>大家爱看</Text>
        {/*<LiteratureList data={literatureData} />*/}
        {/*文件列表*/}
        <FlatList showsVerticalScrollIndicator={false}
                  style={listStyles.box} renderItem={renderItem}
                  data={literatureData}
                  ListEmptyComponent={() => (<Empty />)}
                  ListFooterComponent={() => (<ListFooter isList={false} />)}

        />
      </View>
    </View>
  );
};

export default Home;

// 轮播样式
const bannerStyles = StyleSheet.create({
  box: {
    height: 120,
    minHeight: 120
  },
  item: {
    width: windowWidth,
    position: "relative",
    height: 120
  },
  img: {
    width: "100%",
    height: 120
  },
  title: {
    width: "100%",
    position: "absolute",
    left: 0,
    bottom: 0,
    backgroundColor: "rgba(0,0,0,.3)",
    fontSize: 12,
    textAlign: "center",
    color: "#fff",
    paddingTop: 5,
    paddingBottom: 5
  }
});

// 轮播指示点
const indicateStyles = StyleSheet.create({
  box: {
    display: "flex",
    alignItems: "center",
    transform: [{ translateY: 3 }]
  },
  inner: {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    flexDirection: "row",
    minWidth: 30,
    maxWidth: 30,
    paddingRight: 2
  },
  item: {
    width: 6,
    height: 3,
    backgroundColor: "#aaa",
    marginLeft: 2,
    borderRadius: 1
  },
  active: {
    backgroundColor: "#1677ff",
    width: 13,
    height: 3,
    marginLeft: 2,
    borderRadius: 3
  }
});

const literatureStyles = StyleSheet.create({
  box: {
    marginTop: 10,
    width: "100%",
    minHeight: windowHeight - 120 - 30 - 3,
    display: "flex"
  },
  title: {
    marginBottom: 10,
    paddingLeft: 10,
    color: "#111",
    fontWeight: "900",
    borderLeftWidth: 6,
    borderLeftColor: "#1677ff",
    borderStyle: "solid",
    fontSize: 16
  }
});

const listStyles = StyleSheet.create({
  box: {
    width: windowWidth,
    paddingLeft: 10,
    paddingRight: 10,
    flex: 1,
    marginBottom: 110
  }
});
